package com.ziven.common.widget.value;

import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.constraintlayout.widget.ConstraintLayout;

import com.ziven.easygo.util.LogHelper;
import com.ziven.easygo.util.ViewHelper;

import java.lang.reflect.Field;

/**
 * @author Ziven
 */
public class ConstraintValue extends Value {

    private static final String TAG = "ConstraintValue";

    public static ConstraintValue constraint(String constraintName, int constraint) {
        return new ConstraintValue(constraintName, constraint);
    }

    private ConstraintValue(String constraintName, int constraint) {
        value = constraint;
        id = constraintName;
    }

    @Override
    protected void takeEffect(@NonNull ViewHelper<? extends View> helper) {
        if(!(value instanceof Integer) || !(id instanceof String)) {
            return;
        }
        int constraint = (int) value;
        String constraintName = (String) id;
        helper.getViewNulls().doNotNull(view -> {
            ConstraintLayout.LayoutParams layoutParams;
            ViewGroup.LayoutParams params = view.getLayoutParams();
            if(params instanceof ConstraintLayout.LayoutParams) {
                layoutParams = (ConstraintLayout.LayoutParams) params;
            } else if(params instanceof ViewGroup.MarginLayoutParams) {
                layoutParams = new ConstraintLayout.LayoutParams((ViewGroup.MarginLayoutParams) params);
            } else if(params != null) {
                layoutParams = new ConstraintLayout.LayoutParams(params);
            } else {
                layoutParams = new ConstraintLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            }
            try {
                Field method = ConstraintLayout.class.getDeclaredField(constraintName);
                method.setAccessible(true);
                method.setInt(layoutParams, constraint);
                view.setLayoutParams(layoutParams);
            } catch (NoSuchFieldException | IllegalAccessException e) {
                LogHelper.log(TAG, e);
            }
        });
    }
}
